package com.oocl.crm.ui;

import java.io.InputStream;
import java.io.OutputStream;
import java.util.Scanner;

import com.oocl.crm.command.BaseReceiver;
import com.oocl.crm.command.Command;
import com.oocl.crm.command.impl.ConcreteCommand;
import com.oocl.crm.command.receiver.*;
import com.oocl.crm.exception.CrmException;
import com.oocl.crm.util.FormatPrinter;

public class CrmUI {
	
	private InputStream in;
	private OutputStream out;
	
	public CrmUI(InputStream in, OutputStream out) {
		this.in = in;
		this.out = out;
	}

	public void start() {
		Command command;
		BaseReceiver receiver;
		Scanner scanner = new Scanner(in);
		String reader;
		
		try {
			receiver = new ShowHelpReceiver(null);
			command = new ConcreteCommand(receiver);
			FormatPrinter.println(command.execute(),out);
		} catch (CrmException e) {
			FormatPrinter.println(e.getMessage(), out);
		}
		
		while (!(reader = scanner.nextLine()).equals("Q")) {
			try {
				String[] cmdSplit = reader.split(" ");
				switch (cmdSplit[0]) {
				case "L":
					receiver = new ListReceiver(cmdSplit);
					break;
				case "A":
					receiver = new AddReceiver(cmdSplit);
					break;
				case "D":
					receiver = new DeleteReceiver(cmdSplit);
					break;
				case "U":
					receiver = new UpdateReceiver(cmdSplit);
					break;
				case "O":
					receiver = new SortReceiver(cmdSplit);
					break;
				case "H":
					receiver = new ShowHelpReceiver(cmdSplit);
					break;
				default:
					receiver = new ShowHelpReceiver(cmdSplit);
					break;
				}
				
				command = new ConcreteCommand(receiver);
				FormatPrinter.println(command.execute(), out);
			} catch (CrmException e) {
				FormatPrinter.println(e.getMessage(), out);
				continue;
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		FormatPrinter.println("Bye.", out);
		scanner.close();
	}
	
}
